/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.ems.web;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.ems.entity.EmsDept;
import com.thinkgem.jeesite.modules.ems.entity.EmsMajor;
import com.thinkgem.jeesite.modules.ems.service.EmsDeptService;
import com.thinkgem.jeesite.modules.ems.service.EmsMajorService;

/**
 * 专业Controller
 * @author zad
 * @version 2018-01-25
 */
@Controller
@RequestMapping(value = "${adminPath}/ems/emsMajor")
public class EmsMajorController extends BaseController {

	@Autowired
	private EmsMajorService emsMajorService;
	
	@Autowired
	private EmsDeptService emsDeptService;
	
	@ModelAttribute
	public EmsMajor get(@RequestParam(required=false) String id) {
		EmsMajor entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = emsMajorService.get(id);
		}
		if (entity == null){
			entity = new EmsMajor();
		}
		return entity;
	}
	
	@RequiresPermissions("ems:emsMajor:view")
	@RequestMapping(value = {"list", ""})
	public String list(EmsMajor emsMajor, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		// add by zad 2018-01-25 部门查询
		List<EmsDept> depts = this.emsDeptService.findList(null);
		model.addAttribute("depts", depts);
		
		Page<EmsMajor> page = emsMajorService.findPage(new Page<EmsMajor>(request, response), emsMajor); 
		model.addAttribute("page", page);
		return "modules/ems/emsMajorList";
	}

	@RequiresPermissions("ems:emsMajor:view")
	@RequestMapping(value = "form")
	public String form(EmsMajor emsMajor, Model model) {
		
		// add by zad 2018-01-25 部门查询
		List<EmsDept> depts = this.emsDeptService.findList(null);
		model.addAttribute("depts", depts);
		
		model.addAttribute("emsMajor", emsMajor);
		return "modules/ems/emsMajorForm";
	}

	@RequiresPermissions("ems:emsMajor:edit")
	@RequestMapping(value = "save")
	public String save(HttpServletRequest request, HttpServletResponse response,EmsMajor emsMajor, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, emsMajor)){
			return form(emsMajor, model);
		}
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 
		 String dateStr = DateUtils.getDate("yyyy/MM/dd");
		 
	     /** 构建文件保存的目录* */
	      String logoPathDir = "userfiles/1/images/cms/major/logo/" + dateStr + "/";
	      /** 得到文件保存目录的真实路径* */
	      /*String logoRealPathDir = request.getSession().getServletContext()
	              .getRealPath(logoPathDir);*/
	      String logoRealPathDir = Global.getUserfilesBaseDir()+logoPathDir;
	      
	      /** 根据真实路径创建目录* */
	      File logoSaveFile = new File(logoRealPathDir);
	      if (!logoSaveFile.exists())
	      {
	          logoSaveFile.mkdirs();
	      }
	      /** 页面控件的文件流* */
	      MultipartFile multipartFile = multipartRequest.getFile("file");
	      if(multipartFile.getSize() > 0){
	    	  /** 获取文件的后缀* */
	          //String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
	                  
	          /** 使用UUID生成文件名称* */
	          //String logImageName = UUID.randomUUID().toString() + suffix;// 构建文件名称
	          String logImageName = multipartFile.getOriginalFilename();// 构建文件名称
	                  
	          /** 拼成完整的文件保存路径加文件* */
	          String fileName = logoRealPathDir + File.separator + logImageName;
	          File file = new File(fileName);
	          try {
	              multipartFile.transferTo(file);
	          } catch (IllegalStateException e) {
	              e.printStackTrace();
	          } catch (IOException e) {
	              e.printStackTrace();
	          }
	          emsMajor.setLogo(request.getContextPath() + "/"+logoPathDir+logImageName);
	      }
		
		emsMajorService.save(emsMajor);
		addMessage(redirectAttributes, "保存专业成功");
		return "redirect:"+Global.getAdminPath()+"/ems/emsMajor/?repage";
	}
	
	@RequiresPermissions("ems:emsMajor:edit")
	@RequestMapping(value = "delete")
	public String delete(EmsMajor emsMajor, RedirectAttributes redirectAttributes) {
		emsMajorService.delete(emsMajor);
		addMessage(redirectAttributes, "删除专业成功");
		return "redirect:"+Global.getAdminPath()+"/ems/emsMajor/?repage";
	}

	// add by zad 2018-01-26 根据部门查询专业 ，用于添加课程时
	@RequestMapping("qryMajorByDept")
	public String qryMajorByDept(String deptId, HttpServletRequest req,HttpServletResponse rsp)
	{
		EmsMajor major = new EmsMajor();
		EmsDept dept = new EmsDept();
		major.setDept(dept);
		dept.setId(deptId);
		List<EmsMajor> majors = this.emsMajorService.findList(major);
		// 没有专业时
		if(null == majors || majors.size() < 1)
		{
			majors = new ArrayList<EmsMajor>();
			EmsMajor initMajor = new EmsMajor();
			initMajor.setId("");
			initMajor.setName("---请选择---");
			majors.add(initMajor);
		}
		String jsonStr = JsonMapper.toJsonString(majors);
		try {
			rsp.getWriter().print(jsonStr);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}